package auto.app.controller;


import auto.app.controller.from.menus.MenusAddFrom;
import auto.app.controller.from.menus.MenusUpdateFrom;
import auto.app.controller.from.menus.updateRuleMenusFrom;
import auto.app.controller.info.MenusInfo;
import auto.app.dao.MenusDao;
import auto.app.exetion.HibernateExetion;
import auto.app.exetion.MainExection;
import auto.app.model.Menus;
import auto.app.model.RuleMenus;
import auto.app.service.MenusService;
import auto.app.service.RuleMenusService;
import auto.app.util.CommonUtil;
import auto.app.util.ObjectNull;
import auto.app.util.Result;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.xmlbeans.impl.xb.xsdschema.Public;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.*;
import java.util.function.Consumer;
import java.util.stream.Collectors;

import static auto.app.exetion.MainExetionMessage.MENUSISSHIYONG;
import static auto.app.exetion.MainExetionMessage.MENUSNOTSAVE;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 杨森
 * @since 2022-07-08
 */
@RestController
@RequestMapping("/menus")
@Api(value = "菜单管理",tags = "菜单管理")
public class MenusController {

    @Autowired
    private MenusService menusService;

    @Autowired
    private RuleMenusService ruleMenusService;

    @Autowired
    private MenusDao menusDao;

    @GetMapping(value = "/slectMenus/{id}",name = "查询账户菜单权限")
    @ApiOperation(value = "查询账户菜单权限",notes = "查询账户菜单权限")
    public Result<List<MenusInfo>> slectMenus(@PathVariable("id")  Integer id) throws MainExection {
//        CommonUtil.bindingResult(bindingResult);
        List<MenusInfo> menusInfos = menusService.slectWoniuMenus(id);
        return Result.getInstanceList(MenusInfo.class).setData(menusInfos);
    }

    @PostMapping(name = "新增菜单")
    @ApiOperation(value = "新增菜单",notes = "新增菜单")
    public Result<Boolean> addMenus(@Valid @RequestBody MenusAddFrom menusAddFrom) throws MainExection {
        //TODO 11/9好新增菜单
        Boolean aBoolean = menusService.addMenus(menusAddFrom);
        return Result.getInstance(Boolean.class).setData(aBoolean);
    }

    @GetMapping(value = "/{menusId}",name = "菜单回显")
    @ApiOperation(value = "菜单回显",notes = "菜单回显")
    public Result<Menus> detailMenus(@PathVariable String menusId) throws MainExection {
        Menus menusServiceById = menusService.getById(menusId);
        if (ObjectUtil.isNull(menusServiceById)){
            throw new MainExection(MENUSNOTSAVE.getCode(),MENUSNOTSAVE.getMsg());
        }
        return Result.getInstance(Menus.class).setData(menusServiceById);
    }

    @PutMapping(name = "编辑菜单")
    @ApiOperation(value = "编辑菜单",notes = "编辑菜单")
    public Result<Boolean> updateMenus(@Valid @RequestBody MenusUpdateFrom menusUpdateFrom) throws MainExection {
        Boolean aBoolean = menusService.updateMenus(menusUpdateFrom);
        return Result.getInstance(Boolean.class).setData(aBoolean);
    }

    @GetMapping(name = "菜单分页")
    @ApiOperation(value = "菜单分页",notes = "菜单分页")
    public Result<Page> pageMenus(@RequestParam(value = "menusName",required = false) String menusName,Page IPage){
        Page<Menus> page = menusService.page(IPage, new LambdaQueryWrapper<Menus>().like(ObjectNull.isNotNull(menusName), Menus::getMenusName, menusName)
                //查询出仅为父级节点 进行层级展示
                .eq(Menus::getMenusType,0)
                .orderByDesc(Menus::getCreateTime));
        List<Menus> records = page.getRecords();
        QueryWrapper<Menus>queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("menus_type",1);
        List<Menus> menusList = menusService.list(queryWrapper);
        //把叶子节点按父级id分组
        Map<Integer, List<Menus>> collect = menusList.stream().collect(Collectors.groupingBy(Menus::getMenusParentid));
        //对非叶子节点进行赋值
        records.forEach(menus -> {
            List<Menus> list = collect.get(menus.getMenusId());
            if (ObjectUtil.isNotNull(list) && list.size()>0){
                menus.setChildren(list);
            }
        });
        page.setRecords(records);
        return Result.getInstance(Page.class).setData(page);
    }

    @GetMapping(value = "/allMenusRule",name = "返回所有菜单树形结构")
    @ApiOperation(value = "返回所有菜单树形结构",notes = "返回所有菜单树形结构")
    public Result<List<Menus>> allMenusRule(){
            //返回父节点
            QueryWrapper<Menus>queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("menus_type",0);
            List<Menus> list = menusService.list(queryWrapper);
            //返回子节点
            QueryWrapper<Menus>queryWrappernew=new QueryWrapper<>();
            queryWrapper.eq("menus_type",1);
            List<Menus> menusList = menusService.list(queryWrappernew);
            //把叶子节点按父级id分组
            Map<Integer, List<Menus>> collect = menusList.stream().collect(Collectors.groupingBy(Menus::getMenusParentid));

            list.forEach(menus -> {
                List<Menus> listnew = collect.get(menus.getMenusId());
                if (ObjectUtil.isNotNull(listnew) && listnew.size()>0){
                    menus.setChildren(listnew);
                }
            });
            return Result.getInstanceList(Menus.class).setData(list);
    }

    @GetMapping(value = "/allMenusRuleId",name = "返回角色对应菜单的ID")
    @ApiOperation(value = "返回角色对应菜单的ID",notes = "返回角色对应菜单的ID")
    public Result<List<Integer>> allMenusRuleId(@RequestParam(value = "ruleId", required = true) Integer ruleId){
        List<Menus> menusList = menusDao.findMenusByRuleId(ruleId);
        List<Integer> integerList = menusList.stream().map(Menus::getMenusId).collect(Collectors.toList());
        return Result.getInstanceList(Integer.class).setData(integerList);
    }

    @PostMapping(value = "/updateRuleMenus",name = "修改角色的菜单")
    @ApiOperation(value = "修改角色的菜单",notes = "修改角色的菜单")
    public Result<Boolean>updateRuleMenus(@Valid @RequestBody updateRuleMenusFrom updateRuleMenusFrom) throws HibernateExetion {
        Boolean aBoolean = menusService.updateRuleMenus(updateRuleMenusFrom);
        return Result.getInstance(Boolean.class).setData(aBoolean);
    }
    @DeleteMapping(value = "/{menusId}",name = "删除菜单")
    @ApiOperation(value = "删除菜单",notes = "删除菜单")
    @Transactional(rollbackFor = Exception.class)
    public Result<Boolean> deleteMenus(@PathVariable Integer menusId) throws MainExection {
        List<RuleMenus> list = ruleMenusService.list(new LambdaQueryWrapper<RuleMenus>().eq(RuleMenus::getMenusId, menusId));
        if (ObjectUtil.isNotNull(list) && list.size()>0){
            throw new MainExection(MENUSISSHIYONG.getCode(),MENUSISSHIYONG.getMsg());
        }
        boolean b = menusService.removeById(menusId);
        return Result.getInstance(Boolean.class).setData(b);
    }

    @GetMapping(value = "/getAllParant",name = "获取所有父级ID")
    @ApiOperation(value = "获取所有父级ID",notes = "获取所有父级ID")
    public List<Map<String, String>> getAllParant(){
        List<Map<String, String>> maps =new ArrayList<>();
        List<Menus> menusList = menusService.list(new LambdaQueryWrapper<Menus>()
                .eq(Menus::getMenusType, 0)
                .orderByDesc(Menus::getCreateTime));
        for (Menus menus : menusList) {
            HashMap<String,String> hashMap=new HashMap<>();
            hashMap.put("label",menus.getMenusName());
            hashMap.put("value",menus.getMenusId().toString());
            maps.add(hashMap);
        }
        HashMap<String,String> hashMap=new HashMap<>();
        hashMap.put("label","无父级ID");
        hashMap.put("value","0");
        maps.add(hashMap);
        return maps;
    }
}

